//
//  RHInverterParamterCell.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/6/13.
//

#import "RHInverterParamterCell.h"
#import "RHInverterParaTitleCell.h"
#import "RHInverterParaContentCell.h"

@interface RHInverterParamterCell()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIView *itemView;//上面的按钮

@property (nonatomic, assign) NSInteger itemIndex;

@property (nonatomic, strong) NSMutableArray *btnArray;

@property (nonatomic, strong) UIView *scrollContentView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIScrollView *tableScrollView;
@end
@implementation RHInverterParamterCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
    }
    return self;
}

-(void)setModel:(RHInverterModel *)model
{
    _model = model;
    self.itemIndex = model.selectIndex;
    self.modelArray = model.rowDataArr;
}

-(void)setModelArray:(NSArray<RHInverterModel *> *)modelArray
{
    _modelArray = modelArray;
    NSMutableArray *titleArr = [NSMutableArray array];
    [modelArray enumerateObjectsUsingBlock:^(RHInverterModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [titleArr addObject:obj.title.rh_localized];
    }];
    //标题个数
    NSInteger btnCount = titleArr.count<4?titleArr.count:4;
    __block CGFloat itemWidth = (kUI_WINDOW_W - 30 - (btnCount-1)*10)/btnCount;
    //对button重新布局
    [self.btnArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    __block QMUIButton *lastItem;
    [titleArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx < self.btnArray.count) {
            QMUIButton *btn = self.btnArray[idx];
            [self.scrollContentView addSubview:btn];
            [btn setTitle:title forState:UIControlStateNormal];
            
            [btn mas_remakeConstraints:^(MASConstraintMaker *make) {
                
                
                if(lastItem){
                    make.left.equalTo(lastItem.mas_right).offset(10);
                    make.size.centerY.equalTo(lastItem);
                }else{
                    make.left.mas_offset(0);
                    make.height.offset(45);
                    make.width.offset(itemWidth);
                    make.top.mas_offset(0);
                }
            }];
            if(idx == titleArr.count-1){
                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_offset(0);
                }];
                
            }
            lastItem = btn;
        }
    }];
   
    
    [self updateTableView];
    
}

-(void)updateTableView
{
    RHInverterModel *rowModel = self.modelArray[self.model.selectIndex];
    NSLog(@"---->返回%ld",rowModel.itemArr.count);
    
    NSInteger count = rowModel.horizontalTitle.count;
    //如果超过3个以上,按3个的宽度计算
    if (count>3) {
        count = 3;
    }
    //左边第一个标题lebel的宽度
    CGFloat titleWidth = 70;
    CGFloat itemtMargin = 5;
    CGFloat labelWidth = (kUI_WINDOW_W - 30 - titleWidth - ((count+1)*itemtMargin))/count;
    
    //根据每个界面的行数更新高度
    [self.tableScrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset((rowModel.itemArr.count+1)*35);
    }];
    
    CGFloat addWidth = 0;
    if (rowModel.horizontalTitle.count>3) {
        addWidth = (rowModel.horizontalTitle.count-3)*labelWidth + 10;
    }
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset((rowModel.itemArr.count+1)*35);
        make.width.offset(kUI_WINDOW_W-30+addWidth);//更新横向滚动范围
    }];
    
    //如果没有水平标题,减少一行的高度
    if(rowModel.horizontalTitle.count == 0){
        [self.tableScrollView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.offset(rowModel.itemArr.count*35);
        }];
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.offset((rowModel.itemArr.count)*35);
        }];
    }
    
    [self.tableView reloadData];
    
}

- (void)setupUI{
    self.contentView.backgroundColor = CFTabViewBgColor;
    UIView *bgView = kView;
    bgView.backgroundColor = CFTabViewBgColor;
//    bgView.layer.cornerRadius = 8;
//    bgView.layer.masksToBounds = YES;
    [self.contentView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    
    _itemView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [bgView addSubview:_itemView];
    [_itemView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.height.offset(55);
    }];
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.contentInset = UIEdgeInsetsMake(0, 15, 0, 15);
    [_itemView addSubview:scrollView];
    UIView *scrollContentView = kView;
    [scrollView addSubview:scrollContentView];
    self.scrollContentView = scrollContentView;
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    [scrollContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.height.equalTo(scrollView);
    }];
    
    self.btnArray = [NSMutableArray array];
    NSArray *titles = @[@"--",@"--",@"--",@"--",@"--",@"--",@"--",@"--",@"--",@"--"];
    CGFloat itemWidth = (kUI_WINDOW_W - 30 - 30)/4;
    __block QMUIButton *lastItem;
    [titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUIButton *btn = [[QMUIButton alloc]init];
        [btn setTitle:obj forState:UIControlStateNormal];
        btn.titleLabel.font = kSYSTEMFONT(14);
        btn.titleLabel.numberOfLines = 2;
        btn.titleLabel.adjustsFontSizeToFitWidth = YES;
        btn.titleLabel.minimumScaleFactor = 0.8;
        [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.8] forState:UIControlStateNormal];
        btn.backgroundColor = kCOLOR_HEX(@"F6F8FA");
        btn.layer.cornerRadius = 8;
        btn.userInteractionEnabled = YES;
        [btn setBackgroundColor:UIColor.whiteColor];
        [scrollContentView addSubview:btn];
        [self.btnArray addObject:btn];
//        CGFloat btnWidth = [obj getStringWidthFont:btn.titleLabel.font limitHeight:30] +40;
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            
            if(lastItem){
                make.left.equalTo(lastItem.mas_right).offset(10);
                make.size.centerY.equalTo(lastItem);
            }else{
                make.left.mas_offset(0);
                make.height.offset(45);
                make.width.offset(itemWidth);
                make.centerY.mas_offset(0);
            }
        }];
        if(idx == titles.count-1){
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_offset(0);
            }];
            
        }
        lastItem = btn;
        kWeakSelf;
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            weakSelf.model.selectIndex = idx;
            weakSelf.itemIndex = idx;
            [weakSelf updateTableView];
            if(weakSelf.refreshBlock){
                weakSelf.refreshBlock();
            }
        }];
        
        [RACObserve(self, itemIndex) subscribeNext:^(id  _Nullable x) {
            if([x integerValue] == idx){
                [btn setTitleColor:[UIColor colorWithHexString:@"ffffff" alpha:1] forState:UIControlStateNormal];
                [btn setBackgroundColor:CMainColorGreen];
            }else{
                [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.6] forState:UIControlStateNormal];
                [btn setBackgroundColor:UIColor.whiteColor];
            }
        }];
   
    }];
    kWeakSelf;
    
    _tableScrollView = [[UIScrollView alloc]init];
//    _tableScrollView.backgroundColor = UIColor.grayColor;
    _tableScrollView.showsHorizontalScrollIndicator = NO;
    _tableScrollView.showsVerticalScrollIndicator = NO;
    _tableScrollView.alwaysBounceVertical = NO;
    [_tableScrollView rounded:8 width:1 color:kBorderColor];
    
    [bgView addSubview:_tableScrollView];
    [_tableScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.itemView.mas_bottom);
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(40);
        make.bottom.mas_offset(0);
    }];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 40) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    [_tableScrollView addSubview:_tableView];
   
    [_tableView registerClass:[RHInverterParaTitleCell class] forCellReuseIdentifier:@"RHInverterParaTitleCell"];
    [_tableView registerClass:[RHInverterParaContentCell class] forCellReuseIdentifier:@"RHInverterParaContentCell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(weakSelf.itemView.mas_bottom);
//        make.left.right.mas_offset(0);
//        make.height.offset(40);
//        make.bottom.mas_offset(0);
        make.edges.insets(UIEdgeInsetsZero);
        make.width.offset(kUI_WINDOW_W-30);
       
    }];
    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    RHInverterModel *rowModel = self.modelArray[self.model.selectIndex];
    NSLog(@"---->返回%ld",rowModel.itemArr.count);
    //有标题加多一栏
    if (rowModel.horizontalTitle.count>0) {
        return rowModel.itemArr.count+1;
    }
    return rowModel.itemArr.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    RHInverterModel *rowModel = self.modelArray[self.model.selectIndex];
    //水平标题(第一行)
    if (indexPath.row == 0 && rowModel.horizontalTitle.count>0) {
        RHInverterParaTitleCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"RHInverterParaTitleCell"];
        [titleCell setTitleArr:rowModel.horizontalTitle unitArr:rowModel.horizontalUnit];
        return titleCell;
    }
    //内容
    RHInverterParaContentCell *contentCell = [tableView dequeueReusableCellWithIdentifier:@"RHInverterParaContentCell"];
    
    //内容左边第一个标题
    NSString *title = [rowModel.verticalTitle safeObjectAtIndex:indexPath.row];
    NSString *unit = ValidNullData([rowModel.verticalUnit safeObjectAtIndex:indexPath.row]);
    contentCell.modelArray = [rowModel.itemArr safeObjectAtIndex:indexPath.row];
    if (rowModel.horizontalTitle.count>0) {//有标题的加多了一行,所以要减少
        title = [rowModel.verticalTitle safeObjectAtIndex:indexPath.row-1];
        unit = ValidNullData([rowModel.verticalUnit safeObjectAtIndex:indexPath.row-1]);
        contentCell.modelArray = [rowModel.itemArr safeObjectAtIndex:indexPath.row-1];
    }
    
    //只有一个参数的情况,使用后台翻译
    if (contentCell.modelArray.count != 1) {
        if (unit.length==0) {
            contentCell.titleLab.text = title.rh_localized;
        }else{
            NSString *titleStr = [NSString stringWithFormat:@"%@ %@",title.rh_localized,unit];
            //有单位的才使用富文本,不然会崩
            contentCell.titleLab.attributedText = [self attrStringWithContent:titleStr attrKey:unit];
        }
    }
    
    contentCell.bgView.backgroundColor = (indexPath.row %2)?CFTabViewBgColor:UIColor.whiteColor;
//    if(rowModel.itemArr.count == 1){//如果只有一行,不包括标题
//        contentCell.bgView.backgroundColor = UIColor.whiteColor;
//    }
    //最后一行圆角,白色背景 ,第一行是标题的情况下
    if(indexPath.row == rowModel.itemArr.count){
        contentCell.bgView.layer.cornerRadius = 8;
        contentCell.bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
        contentCell.bgView.layer.masksToBounds = YES;
        contentCell.bgView.backgroundColor = UIColor.whiteColor;
    }else{
        contentCell.bgView.layer.cornerRadius = 0;
    }
    
    //如果没有标题的情况
    if (rowModel.horizontalTitle.count == 0) {
        if (indexPath.row == rowModel.itemArr.count-1) {
            contentCell.bgView.layer.cornerRadius = 8;
            contentCell.bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
            contentCell.bgView.layer.masksToBounds = YES;
            contentCell.bgView.backgroundColor = UIColor.whiteColor;
        }
        if (rowModel.itemArr.count == 1) {
            contentCell.bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner|kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
        }
    }
    
    return contentCell;
    
    return [UITableViewCell new];
}

-(NSAttributedString*)attrStringWithContent:(NSString *)content  attrKey:(NSString*)key
{
    
    if(![content containsString:ValidNullData(key)]){
        return [[NSMutableAttributedString alloc] initWithString:content];
    }
    NSDictionary *attiDic = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:10],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"3F4443" alpha:0.6]};
    
    NSMutableAttributedString *attri_content = [[NSMutableAttributedString alloc] initWithString:content];
    [attri_content setAttributes:attiDic range:[content rangeOfString:key]];
    return attri_content;
}

@end
